# -*- coding: utf-8 -*-

# -------------------------------
# Author    : linlingwei
# Email     : 951035650@qq.com
# File Name : curveCore.py
# Date      : 2018/11/5
# IDE       : PyCharm
# Version   : 1.0.1
# -------------------------------


__author__ = "lin lingwei"

import os

import maya.cmds as mc
import maya.mel as mel
import pymel.core as pm

import configs.constants.suffix_constant as sc

import scripts.commonCmds as cCore

# reload(cCore)

dataFormat = ".crvData"
scriptRoot = os.environ["DEV_SCRIPT_DIR"]
controlRoot = os.path.join(scriptRoot, r"configs\controlData")
controlData = os.path.join(controlRoot, "crvData")
controlIcon = os.path.join(controlRoot, "icon")


def exportData(crvObj, path=controlData, fname="test"):
    crvShape = cCore.findRelatedShape(crvObj)
    if mc.nodeType(crvShape) != "nurbsCurve":
        return
    crvNode = pm.PyNode(crvShape)
    degree = crvNode.degree()
    spans = crvNode.numSpans()
    form = mc.getAttr("{}.form".format(crvShape))
    dimension = "no"
    isRational = "3"
    knotCount = crvNode.numKnots()
    knotValue = crvNode.getKnots()
    points = crvNode.getCVs()
    numCVs = len(points)
    
    crvData = [degree, spans, form, dimension, isRational,
               knotCount]
    for value in knotValue:
        crvData.append(int(value))
    crvData.append(numCVs)
    
    for pt in points:
        crvData.append(pt[0])
        crvData.append(pt[1])
        crvData.append(pt[2])
    
    outCrvData = " ".join([str(_) for _ in crvData])
    
    with open(os.path.join(path, fname), "w") as fp:
        fp.write(outCrvData)
    
    return


def getData(obj):
    crvShape = cCore.findRelatedShape(obj)
    if mc.nodeType(crvShape) != "nurbsCurve":
        return
    crvNode = pm.PyNode(crvShape)
    degree = crvNode.degree()
    spans = crvNode.numSpans()
    form = mc.getAttr("{}.form".format(crvShape))
    dimension = "no"
    isRational = "3"
    knotCount = crvNode.numKnots()
    knotValue = crvNode.getKnots()
    points = crvNode.getCVs()
    numCVs = len(points)
    
    crvData = [degree, spans, form, dimension, isRational,
               knotCount]
    for value in knotValue:
        crvData.append(int(value))
    crvData.append(numCVs)
    
    for pt in points:
        crvData.append(pt[0])
        crvData.append(pt[1])
        crvData.append(pt[2])
    
    outCrvData = " ".join([str(_) for _ in crvData])
    
    return outCrvData


def setData(obj, data):
    crvShape = cCore.findRelatedShape(obj)
    cmd = 'setAttr "{}.cc" -type "nurbsCurve" {};'.format(crvShape, data)
    mel.eval(cmd)
    return


def importData(crvObj, path, fname):
    with open(os.path.join(path, fname + dataFormat), 'r') as fp:
        crvData = fp.read()
    
    crvShape = mc.createNode("nurbsCurve", name=crvObj + "Shape", p=crvObj)
    cmd = 'setAttr "{}.cc" -type "nurbsCurve" {};'.format(crvShape, crvData)
    mel.eval(cmd)
    
    return crvShape


def scale(crvObj, x=1, y=1, z=1):
    cv = mc.ls('%s.cv[*]' % crvObj, fl=1)
    
    for i in range(len(cv)):
        obj = '%sShape.controlPoints[%s]' % (crvObj, i)
        _x = mc.getAttr('%s.xValue' % obj)
        _y = mc.getAttr('%s.yValue' % obj)
        _z = mc.getAttr('%s.zValue' % obj)
        
        mc.setAttr('%s.xValue' % obj, _x * x)
        mc.setAttr('%s.yValue' % obj, _y * y)
        mc.setAttr('%s.zValue' % obj, _z * z)
    
    return


def scaleXYZ(crvObj, xyz=1):
    scale(crvObj, xyz, xyz, xyz)
    return


def addShape(obj, shapeName="circle", colorId=0):
    dataDir = os.listdir(controlData)
    if shapeName + dataFormat not in dataDir:
        return
    shape = importData(obj, controlData, shapeName)
    cCore.changColor(shape, colorId)
    return shape


def createControl(ctrName, shapeName="circle", colorId=0):
    ctr = mc.createNode("transform", name=ctrName)
    addShape(ctr, shapeName, colorId)
    return ctr


def replaceShape(obj, shapeName="circle", colorId=0):
    oldShape = mc.listRelatives(obj, s=True)
    mc.delete(oldShape)
    shape = addShape(obj, shapeName, colorId)
    return shape


def changColor(obj, colorId=0):
    shape = cCore.findRelatedShape(obj)
    mc.setAttr(shape + ".overrideEnabled", 1)
    mc.setAttr(shape + ".overrideColor", colorId)
    return


def mirrorShape(inObj, outObj, axial="x"):
    incvs = mc.ls('%s.cv[*]' % inObj, fl=1)
    outcvs = mc.ls('%s.cv[*]' % outObj, fl=1)
    
    if len(incvs) == len(outcvs):
        for i in range(len(incvs)):
            obj = '%sShape.controlPoints[%s]' % (inObj, i)
            _x, _y, _z = mc.getAttr(obj)[0]
            if axial == 'x':
                mc.setAttr(obj.replace(inObj, outObj), -_x, _y, _z)
            elif axial == 'y':
                mc.setAttr(obj.replace(inObj, outObj), _x, -_y, _z)
            elif axial == 'z':
                mc.setAttr(obj.replace(inObj, outObj), _x, _y, -_z)
    
    return


def objToControl(obj, name, ctrlShape="circle", colorId=0, scale=1,mirror = False ):
    ctr = createControl(cCore.lname(name, sc.sCtr),
                                shapeName=ctrlShape,colorId=colorId)
    mc.parent(ctr,obj)
    cCore.channelAttrToDefault(ctr)
    mc.parent(ctr,w=True)
    mc.setAttr(ctr+".s",1,1,1)

    if mirror:
        mg = mc.group(em=True)
        mc.parent(ctr,mg)
        mc.setAttr(mg+".sx",-1)
        mc.parent(ctr,w=True)
        mc.delete(mg)
    scaleXYZ(ctr,scale)
    return ctr

def rotate(obj,x=0,y=0,z=0,space="object"):
    # shape = cCore.findRelatedShape(obj)
    piv = mc.xform(obj+".cv[*]",q=True,piv=True,ws=True)[:3]
    # print piv
    mc.rotate(x,y,z,obj+".cv[*]",p=piv,r=True)
    
    return



if __name__ == '__main__':
    pass